//
//  LKPayDataViewController.m
//  Mideleague_Shop
//
//  Created by Zhiwang on 2020/7/1.
//  Copyright © 2020 Zhiwang. All rights reserved.
//

#import "LKPayDataViewController.h"
#import "LKPayDataModel.h"
#import "LKPayDataCell.h"
#import "LKMutableDatePicker.h"
#import "LKUserHelpPictureViewController.h"
@interface LKPayDataViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)LKBaseTableview *tableView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)LKPayDataModel *dataModel;
@property(nonatomic,strong)NSArray *titlesArray;
@property(nonatomic,strong)NSMutableArray *numsArray;
@property(nonatomic,strong)NSMutableArray *valusArray;
@property(nonatomic,assign)NSInteger sectionNumber;
@property(nonatomic,strong)NSMutableArray *payStyleArray;
@property(nonatomic,strong)LKBaseLabel *titleTimeLabel;
@property(nonatomic,strong)WMZDropDownMenu *menu;
@end

@implementation LKPayDataViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"支付数据";
    self.sectionNumber = 0;
    self.titlesArray = @[@"订单总额",@"现金支付",@"退款",@"优惠金额(商户)",@"优惠金额(平台)",@"交易手续费",@"结算金额"];
    [self setNavgationRightBtn];
    [self createMenuView];
    [self createTableview];
    [self getPayDataListWithType:@"1"];
    // Do any additional setup after loading the view.
}
-(void)setNavgationRightBtn{
    WS(weakSelf)
    LKBaseButton *rightBtn = [LKBaseButton buttonWithFrame:CGRectMake(0, 0, 64, 24) type:UIButtonTypeCustom title:@"使用帮助" titleColor:COLOR_HEX(0x333333) layercorne:13 font:[UIFont fontWithName:@"PingFangSC-Regular" size: 16] backgroudColor:[UIColor clearColor] AndActionBlock:^(UIButton * _Nonnull btn) {
        LKUserHelpPictureViewController *vc = [[LKUserHelpPictureViewController alloc] init];
        vc.currentImage = [UIImage imageNamed:@"ic_pay_data_help"];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
}
-(void)back{
    [super back];
    [_menu closeView];
}


-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
        [_menu closeView];
}

-(void)createMenuView{
    WMZDropMenuParam *param =
    MenuParam()
    .wMainRadiusSet(0)
    .wCollectionViewCellSelectTitleColorSet(yellowDefaultColor)
    .wMenuTitleEqualCountSet(2)
    .wDefaultConfirmHeightSet(50)
    .wCollectionViewCellSelectBgColorSet(MenuColor(0xffeceb));
    _menu = [[WMZDropDownMenu alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, WIDTH, 40) withParam:param];
    _menu.delegate = self;
    [self.view addSubview:_menu];
}

-(void)createTableview{
    self.titleTimeLabel = [LKBaseLabel labelWithFrame:CGRectZero text:@"时间" textColor:COLOR_HEX(0x666666) font:[UIFont fontWithName:@"PingFangSC-Regular" size:12] textAlignment:NSTextAlignmentLeft];
    NSString *currentTime = [[NSString getCurrentTime] componentsSeparatedByString:@" "][0];
    self.titleTimeLabel.text = [NSString stringWithFormat:@"%@ 00:00 至 %@ 23:59",currentTime,currentTime];
    [self.view addSubview:self.titleTimeLabel];
    [self.titleTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(NAVIGATION_BAR_HEIGHT + 40);
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(30);
    }];
    self.tableView = [LKBaseTableview setTableviewWithFrame:CGRectZero style:UITableViewStyleGrouped registercellClasss:@[@"LKPayDataCell"]];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.emptyDataSetSource = self;
    _tableView.emptyDataSetDelegate = self;
    _tableView.backgroundColor = viewDefualtColor;
    [self.view addSubview:_tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.titleTimeLabel.mas_bottom).offset(0);
        make.bottom.equalTo(self.view).offset(0);
    }];

    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.payStyleArray.count + 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return self.titlesArray.count;
    }
    return 3;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LKPayDataCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKPayDataCell"];
    cell.lineView.hidden = YES;
    if (indexPath.section == 0) {
        cell.titleLabel.text = self.titlesArray[indexPath.row];
        if (self.numsArray.count != 0) {
            NSString *nums = [NSString stringWithFormat:@"%@",self.numsArray[indexPath.row]];
            if (nums.length != 0) {
                cell.numsLabel.text = [NSString stringWithFormat:@"%@(笔)",self.numsArray[indexPath.row]];
            }else{
                cell.numsLabel.text = self.numsArray[indexPath.row];
            }

                cell.moneyLabel.text = [NSString stringWithFormat:@"￥%@",self.valusArray[indexPath.row]];
            if (indexPath.row == self.numsArray.count - 1) {
                cell.lineView.hidden = NO;
                cell.moneyLabel.textColor = yellowDefaultColor;
            }
        }
        return cell;
    }
    LKPayDataDetailModel *model = self.payStyleArray[indexPath.section - 1];
    if (indexPath.row == 0) {
        cell.titleLabel.text = [NSString backPayDataStyleStrAccordingModelStr:model.type];
        cell.numsLabel.text = [NSString stringWithFormat:@"%@(笔)",model.nums];
        cell.moneyLabel.text = [NSString stringWithFormat:@"￥%@",model.price];
    }
    if (indexPath.row == 1) {
        cell.titleLabel.text = @"交易手续费";
        cell.numsLabel.text = @"";
        cell.moneyLabel.text = model.poundage;
    }
    if (indexPath.row == 2) {
        cell.lineView.hidden = NO;
        cell.titleLabel.text = @"结算金额";
        cell.numsLabel.text = [NSString stringWithFormat:@"%@(笔)",model.nums];
        cell.moneyLabel.text = [NSString stringWithFormat:@"￥%@",model.settle];
        cell.moneyLabel.textColor = yellowDefaultColor;
    }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40.0f;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *header = [[UIView alloc] init];
    header.backgroundColor = [UIColor whiteColor];
    header.alpha = 0.6;
    for (UIView *subview in header.subviews) {
        [subview removeFromSuperview];
    }

    if (section == 0) {
        LKBaseLabel *leftLabel = [LKBaseLabel labelWithFrame:CGRectZero text:@"汇总" textColor:COLOR_HEX(0x666666) font:[UIFont fontWithName:@"PingFangSC-Mediun" size:14] textAlignment:NSTextAlignmentCenter];
        [header addSubview:leftLabel];
        [leftLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(header.mas_left).offset(20);
            make.centerY.equalTo(header);
        }];
        return header;
    }else if(section == 1){
        LKBaseLabel *leftLabel = [LKBaseLabel labelWithFrame:CGRectZero text:@"支付明细" textColor:COLOR_HEX(0x666666) font:[UIFont fontWithName:@"PingFangSC-Mediun" size:14] textAlignment:NSTextAlignmentCenter];
        [header addSubview:leftLabel];
        [leftLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(header.mas_left).offset(20);
            make.centerY.equalTo(header);
        }];
        return header;
    }
    return header;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0 || section == 1) {
        return 36.0f;
    }
    return 10.0f;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [[UIView alloc] init];
    return footerView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0000000001f;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

}

#pragma mark WMZDelegate
- (NSArray*)titleArrInMenu:(WMZDropDownMenu *)menu{
    return @[
         @{@"name":@"今日",@"normalImage":@"menu_dowm",@"selectImage":@"menu_up"},@{@"name":@"全部商户",@"normalImage":@"menu_dowm",@"selectImage":@"menu_up"}
    ];
}


- (NSInteger)menu:(WMZDropDownMenu *)menu numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (NSArray *)menu:(WMZDropDownMenu *)menu dataForRowAtDropIndexPath:(WMZDropIndexPath *)dropIndexPath{
    if (dropIndexPath.section == 0) {
        return @[@"今日",@"昨日",@"本周",@"本月",@"自定义"];
    }else if (dropIndexPath.section == 1) {
        return @[@"全部商户"];
    }
    return @[];
}

- (NSInteger)menu:(WMZDropDownMenu *)menu countForRowAtDropIndexPath:(WMZDropIndexPath *)dropIndexPath{
    return 4;
}

#define titleArr @[@""]
- (NSString*)menu:(WMZDropDownMenu *)menu titleForHeadViewAtDropIndexPath:(WMZDropIndexPath*)dropIndexPath{
        return titleArr[dropIndexPath.row];
}


- (CGFloat)menu:(WMZDropDownMenu *)menu heightForFootViewAtDropIndexPath:(WMZDropIndexPath *)dropIndexPath{
    return 0;
}

- (CGFloat)menu:(WMZDropDownMenu *)menu heightForHeadViewAtDropIndexPath:(WMZDropIndexPath *)dropIndexPath{
    return 0;
}

- (MenuUIStyle)menu:(WMZDropDownMenu *)menu uiStyleForRowIndexPath:(WMZDropIndexPath *)dropIndexPath{
    return MenuUITableView;

}

- (UITableViewCell*)menu:(WMZDropDownMenu *)menu cellForUITableView:(WMZDropTableView *)tableView AtIndexPath:(NSIndexPath *)indexpath dataForIndexPath:(WMZDropTree *)model{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GanJiTableViewCell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"GanJiTableViewCell"];
    }
    cell.textLabel.text = model.name;
    cell.textLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:13];
    cell.textLabel.textColor = model.isSelected?yellowDefaultColor:MenuColor(0x666666);
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    return cell;
}
- (CGFloat)menu:(WMZDropDownMenu *)menu heightAtDropIndexPath:(WMZDropIndexPath *)dropIndexPath AtIndexPath:(NSIndexPath *)indexpath{
    if (dropIndexPath.section == 0 || dropIndexPath.section == 1 || dropIndexPath.section == 2) {
        return 50;
    }
    return 35;
}
- (MenuEditStyle)menu:(WMZDropDownMenu *)menu editStyleForRowAtDropIndexPath:(WMZDropIndexPath *)dropIndexPath{
    return MenuEditOneCheck;
}

/*
*返回section行标题数据视图消失的动画样式   默认 MenuHideAnimalNone
*/
- (MenuHideAnimalStyle)menu:(WMZDropDownMenu *)menu hideAnimalStyleForRowInSection:(NSInteger)section{
            return MenuHideAnimalTop;
}

- (MenuShowAnimalStyle)menu:(WMZDropDownMenu *)menu showAnimalStyleForRowInSection:(NSInteger)section{
            return MenuShowAnimalBottom;
}

- (BOOL)menu:(WMZDropDownMenu *)menu closeWithTapAtDropIndexPath:(WMZDropIndexPath *)dropIndexPath{
    return YES;
}

-(void)menu:(WMZDropDownMenu *)menu didSelectRowAtDropIndexPath:(WMZDropIndexPath *)dropIndexPath dataIndexPath:(NSIndexPath *)indexpath data:(WMZDropTree *)data{
    if (dropIndexPath.section == 0) {
        if (indexpath.row != 4) {
            switch (indexpath.row) {
                case 0:
                {
                  NSString *currentTime = [[NSString getCurrentTime] componentsSeparatedByString:@" "][0];
                  self.titleTimeLabel.text = [NSString stringWithFormat:@"%@ 00:00 至 %@ 23:59",currentTime,currentTime];
                }
                    break;
                case 1:
                {
                    NSDate *preDate = [NSString getPriousorDayLaterDateFromDate:[NSDate date] withDay:-1];
                    NSString *preDayStr = [[NSString getTimeStrAccoringDate:preDate] componentsSeparatedByString:@" "][0];
                     self.titleTimeLabel.text = [NSString stringWithFormat:@"%@ 00:00 至 %@ 23:59",preDayStr,preDayStr];
                }
                    break;
                case 2:
                {
                    NSString *currentTime = [[NSString getCurrentTime] componentsSeparatedByString:@" "][0];
                    NSDate *preDate = [NSString getPriousorDayLaterDateFromDate:[NSDate date] withDay:-7];
                    NSString *preDayStr = [[NSString getTimeStrAccoringDate:preDate] componentsSeparatedByString:@" "][0];
                     self.titleTimeLabel.text = [NSString stringWithFormat:@"%@ 00:00 至 %@ 23:59",preDayStr,currentTime];
                }
                    break;
                case 3:
                {
                    NSString *currentTime = [[NSString getCurrentTime] componentsSeparatedByString:@" "][0];
                    NSDate *preDate = [NSString getPriousorLaterDateFromDate:[NSDate date] withMonth:-1];
                    NSString *preDayStr = [[NSString getTimeStrAccoringDate:preDate] componentsSeparatedByString:@" "][0];
                     self.titleTimeLabel.text = [NSString stringWithFormat:@"%@ 00:00 至 %@ 23:59",preDayStr,currentTime];
                }
                    break;
                default:
                    break;
            }
            [self getPayDataListWithType:[NSString stringWithFormat:@"%ld",indexpath.row + 1]];
        }else{
            WS(weakSelf)
            [LKMutableDatePicker showCustomDatePickerAtView:[UIApplication sharedApplication].keyWindow choosedDateBlock:^(NSString * _Nonnull startTime, NSString * _Nonnull endTime) {
                
                weakSelf.titleTimeLabel.text = [NSString stringWithFormat:@"%@ 00:00 至 %@ 23:59",[startTime componentsSeparatedByString:@" "][0],[endTime componentsSeparatedByString:@" "][0]];
                [self getPayDataListWithType:[NSString stringWithFormat:@"7"]];
            } cancelBlock:^{
                
            }];
        }

    }
}
- (void)menu:(WMZDropDownMenu *)menu didConfirmAtSection:(NSInteger)section selectNoramelData:(NSMutableArray *)selectNoramalData selectStringData:(NSMutableArray *)selectData{
    NSLog(@"选中的数据是%@",selectData);
}
-(NSMutableArray *)numsArray{
    if (_numsArray == nil) {
        _numsArray = [[NSMutableArray alloc] init];
    }
    return _numsArray;
}
-(NSMutableArray *)valusArray{
    if (_valusArray == nil) {
        _valusArray = [[NSMutableArray alloc] init];
    }
    return _valusArray;
}
-(NSMutableArray *)payStyleArray{
    if (_payStyleArray == nil) {
        _payStyleArray = [[NSMutableArray alloc] init];
    }
    return _payStyleArray;
}
-(void)getPayDataListWithType:(NSString *)type{
    //type 1.今天
        NSMutableDictionary *param ;
    if ([type isEqualToString:@"7"]) {
        NSString *startTime = [self.titleTimeLabel.text componentsSeparatedByString:@"至"][0];
        NSString *endTime = [self.titleTimeLabel.text componentsSeparatedByString:@"至"][1];
        NSInteger startStamp = [NSString timeSwitchTimestamp:startTime andFormatter:@"YYYY-MM-dd HH:ss"];
        NSInteger endStamp = [NSString timeSwitchTimestamp:endTime andFormatter:@"YYYY-MM-dd HH:ss"];
        param = [[NSMutableDictionary alloc] initWithDictionary:@{@"type":type,@"start_time":@(startStamp),@"end_time":@(endStamp)}];
    }else{
            param = [[NSMutableDictionary alloc] initWithDictionary:@{@"type":type}];
    }
    NSString *sign = [NSString encoingWithDic:param];
    [param setObject:sign forKey:@"sign"];
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:MyPaydataUrl header:[LKUserInforTool account].token parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        if ([responseObject[@"code"] isEqualToString:@"success"]) {
            self.sectionNumber = 0;
            [self.numsArray removeAllObjects];
            [self.valusArray removeAllObjects];
            [self.payStyleArray removeAllObjects];
            NSDictionary *dataDic = responseObject[@"data"];
            self.dataModel = [LKPayDataModel modelWithDictionary:dataDic];
            [self.numsArray addObjectsFromArray:@[self.dataModel.total_nums,self.dataModel.cash_nums,self.dataModel.back_nums,self.dataModel.discount_num_merchant,self.dataModel.discount_num_platform,@"",@""]];
            [self.valusArray addObjectsFromArray:@[self.dataModel.total_price,self.dataModel.cash_price,self.dataModel.back_price,self.dataModel.discount_price_merchant,self.dataModel.discount_price_platform,self.dataModel.poundage_price,self.dataModel.settle_accounts]];
            for (LKPayDataDetailModel *model in self.dataModel.detail) {
                if ([model.type isEqualToString:@"1"] && [model.nums integerValue] != 0) {
                    [self.payStyleArray addObject:model];
                }
                if ([model.type isEqualToString:@"2"] && [model.nums integerValue] != 0) {
                    [self.payStyleArray addObject:model];
                }
                if ([model.type isEqualToString:@"9"] && [model.nums integerValue] != 0) {
                    [self.payStyleArray addObject:model];
                }
            }
            [self.tableView reloadData];
        }else{
            [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
        }
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
